#include "Atmosphere.h"

AtmosphereMgr::AtmosphereMgr( vPlanet *_planet ) {
	PLN = _planet;
	obj = PLN->obj;
	AtmType = NO_ATMOSPHERE;
}

UINT
	AtmosphereMgr::Stride_HVERTEX = 32,
	AtmosphereMgr::nIdx = HORIZON_NSEG*2 + 2;
ID3D11Buffer
	*AtmosphereMgr::VB = NULL,
	*AtmosphereMgr::IB = NULL;
float
	AtmosphereMgr::COSP[HORIZON_NSEG] = { 0.0f },
	AtmosphereMgr::SINP[HORIZON_NSEG] = { 0.0f };
AtmosphereMgr::HVERTEX
	*AtmosphereMgr::_VB = NULL;
ID3D11InputLayout
	*AtmosphereMgr::IL = NULL;
ID3D11VertexShader
	*AtmosphereMgr::VS = NULL;

void AtmosphereMgr::GlobalInit() {

	HRESULT hr;
	ID3DBlob *SBlob = NULL, *EBlob = NULL;

	D3D11_INPUT_ELEMENT_DESC iedesc[ ] = {
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 }	};

	::CompileFromFile( "Modules\\D3D11Shaders\\Planet\\VS.fx", NULL, NULL, "VS_Atmosphere", vs_ver, ShaderCompileFlag, 0, NULL, &SBlob, &EBlob, &hr );
	ShowShaderCompilationError( hr, EBlob );
	HR( Dev->CreateInputLayout( iedesc, 3, SBlob->GetBufferPointer(), SBlob->GetBufferSize(), &IL ) );
	HR( Dev->CreateVertexShader( SBlob->GetBufferPointer(), SBlob->GetBufferSize(), NULL, &VS ) );
	REL( SBlob );
	REL( EBlob );

	//===============================================
	//				Horizon cone buffers
	//===============================================

	D3D11_BUFFER_DESC desc;
	D3D11_SUBRESOURCE_DATA sdata;

	//Vertex buffer:
	_VB = new HVERTEX [HORIZON_NSEG*2];

	memset( &desc, 0, sizeof(desc) );
	desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	desc.ByteWidth = 2*sizeof(HVERTEX)*HORIZON_NSEG;
	desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	desc.MiscFlags = 0;
	desc.StructureByteStride = 0;
	desc.Usage = D3D11_USAGE_DYNAMIC;

	memset( &sdata, 0, sizeof(sdata) );
	sdata.pSysMem = _VB;

	HR( Dev->CreateBuffer( &desc, &sdata, &VB ) );

	//Index buffer:

	DWORD j = 0, nidx = HORIZON_NSEG*2+2;
	WORD idata[HORIZON_NSEG*2+2];
	for( j = 0; j < HORIZON_NSEG; j++ ) {
		idata[j*2] = (WORD)(j*2+1);
		idata[j*2+1] = (WORD)(j*2);
	}
	idata[j*2] = 1,	idata[j*2+1] = 0;

	memset( &desc, 0, sizeof(desc) );
	desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	desc.ByteWidth = 2*(2*HORIZON_NSEG+2);
	desc.CPUAccessFlags = 0;
	desc.MiscFlags = 0;
	desc.StructureByteStride = 0;
	desc.Usage = D3D11_USAGE_IMMUTABLE;

	memset( &sdata, 0, sizeof(sdata) );
	sdata.pSysMem = idata;

	HR( Dev->CreateBuffer( &desc, &sdata, &IB ) );

	double phi;
	for( j = 0; j < HORIZON_NSEG; j++ ) {
		_VB[j*2].tex = 1.0f;
		_VB[j*2+1].tex = 0.0f;
		phi = (double)j/(double)HORIZON_NSEG*PI2;
		COSP[j] = (float)cos(phi),	SINP[j] = (float)sin(phi);
	}
}

void AtmosphereMgr::GlobalExit() {
	REL( VB );
	REL( IB );
	REL( IL );
	REL( VS );
	delete [ ] _VB;
}